<template>
  <div class="profile-page">
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <span>个人信息</span>
          <el-button 
            v-if="!editMode" 
            type="primary" 
            @click="toggleEditMode"
            :icon="Edit"
          >
            编辑信息
          </el-button>
          <div v-else class="edit-buttons">
            <el-button @click="cancelEdit">取消</el-button>
            <el-button type="primary" @click="saveProfile" :loading="saving">保存</el-button>
          </div>
        </div>
      </template>

      <div v-loading="loading" class="profile-content">
        <!-- 查看模式 -->
        <div v-if="!editMode" class="view-mode">
          <div class="user-info">
            <div class="info-item">
              <label>用户名：</label>
              <span>{{ userInfo.username }}</span>
            </div>
            <div class="info-item">
              <label>真实姓名：</label>
              <span>{{ userInfo.realName || '未设置' }}</span>
            </div>
            <div class="info-item">
              <label>角色：</label>
              <el-tag :type="getRoleTagType(userInfo.role)">
                {{ getRoleDisplayName(userInfo.role) }}
              </el-tag>
            </div>
            <div class="info-item">
              <label>所属部门：</label>
              <span>{{ userInfo.department || '未设置' }}</span>
            </div>
            <div class="info-item">
              <label>手机号码：</label>
              <span>{{ userInfo.phone || '未设置' }}</span>
            </div>
            <div class="info-item">
              <label>邮箱地址：</label>
              <span>{{ userInfo.email || '未设置' }}</span>
            </div>
            <div class="info-item">
              <label>注册时间：</label>
              <span>{{ formatDate(userInfo.createdAt) }}</span>
            </div>
            <div class="info-item">
              <label>最后登录：</label>
              <span>{{ formatDate(userInfo.lastLogin) || '未记录' }}</span>
            </div>
          </div>
        </div>

        <!-- 编辑模式 -->
        <div v-else class="edit-mode">
          <el-form
            ref="profileFormRef"
            :model="profileForm"
            :rules="profileRules"
            label-width="120px"
            class="profile-form"
          >
            <el-form-item label="用户名">
              <el-input v-model="userInfo.username" disabled />
              <div class="form-tip">用户名不可修改</div>
            </el-form-item>

            <el-form-item label="真实姓名" prop="realName">
              <el-input v-model="profileForm.realName" placeholder="请输入真实姓名" />
            </el-form-item>

            <el-form-item label="角色">
              <el-tag :type="getRoleTagType(userInfo.role)">
                {{ getRoleDisplayName(userInfo.role) }}
              </el-tag>
              <div class="form-tip">角色不可修改</div>
            </el-form-item>

            <el-form-item label="所属部门" prop="department">
              <el-input v-model="profileForm.department" placeholder="请输入所属部门" />
            </el-form-item>

            <el-form-item label="手机号码" prop="phone">
              <el-input v-model="profileForm.phone" placeholder="请输入手机号码" />
            </el-form-item>

            <el-form-item label="邮箱地址" prop="email">
              <el-input v-model="profileForm.email" placeholder="请输入邮箱地址" />
            </el-form-item>

            <el-divider>修改密码（可选）</el-divider>

            <el-form-item label="当前密码" prop="currentPassword">
              <el-input 
                v-model="profileForm.currentPassword" 
                type="password" 
                placeholder="如需修改密码，请输入当前密码"
                show-password
              />
            </el-form-item>

            <el-form-item label="新密码" prop="newPassword">
              <el-input 
                v-model="profileForm.newPassword" 
                type="password" 
                placeholder="请输入新密码（6-20位）"
                show-password
              />
            </el-form-item>

            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input 
                v-model="profileForm.confirmPassword" 
                type="password" 
                placeholder="请再次输入新密码"
                show-password
              />
            </el-form-item>
          </el-form>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Edit } from '@element-plus/icons-vue'
import userService from '@/api/user'

interface UserInfo {
  id: number
  username: string
  realName: string
  role: string
  department: string
  phone: string
  email: string
  createdAt: string
  lastLogin: string
  status: number
}

interface ProfileForm {
  realName: string
  department: string
  phone: string
  email: string
  currentPassword: string
  newPassword: string
  confirmPassword: string
}

export default defineComponent({
  name: 'Profile',
  setup() {
    const loading = ref(true)
    const saving = ref(false)
    const editMode = ref(false)
    const profileFormRef = ref()

    const userInfo = ref<UserInfo>({
      id: 0,
      username: '',
      realName: '',
      role: '',
      department: '',
      phone: '',
      email: '',
      createdAt: '',
      lastLogin: '',
      status: 1
    })

    const profileForm = reactive<ProfileForm>({
      realName: '',
      department: '',
      phone: '',
      email: '',
      currentPassword: '',
      newPassword: '',
      confirmPassword: ''
    })

    // 表单验证规则
    const profileRules = {
      realName: [
        { min: 2, max: 20, message: '真实姓名长度必须在2-20个字符之间', trigger: 'blur' }
      ],
      phone: [
        { pattern: /^[1][3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
      ],
      email: [
        { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
      ],
      department: [
        { max: 100, message: '部门名称不能超过100个字符', trigger: 'blur' }
      ],
      newPassword: [
        { min: 6, max: 20, message: '密码长度必须在6-20个字符之间', trigger: 'blur' }
      ],
      confirmPassword: [
        {
          validator: (rule: any, value: string, callback: (error?: Error) => void) => {
            if (profileForm.newPassword && value !== profileForm.newPassword) {
              callback(new Error('两次输入的密码不一致'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }
      ]
    }

    // 获取用户信息
    const loadUserProfile = async () => {
      try {
        loading.value = true
        
        // 先检查认证状态
        try {
          const authStatus = await userService.testAuthStatus()
          console.log('认证状态:', authStatus.data)
          
          if (!authStatus.data.hasAuthentication || !authStatus.data.isAuthenticated) {
            ElMessage.error('用户未登录，请重新登录')
            return
          }
          
          if (!authStatus.data.hasCurrentUser) {
            ElMessage.error('Session中没有用户信息，请重新登录')
            return
          }
        } catch (authError) {
          console.error('检查认证状态失败:', authError)
          ElMessage.error('认证检查失败，请重新登录')
          return
        }
        
        const response = await userService.getCurrentUserProfile()
        userInfo.value = response.data
        
        // 填充编辑表单
        profileForm.realName = userInfo.value.realName || ''
        profileForm.department = userInfo.value.department || ''
        profileForm.phone = userInfo.value.phone || ''
        profileForm.email = userInfo.value.email || ''
        
      } catch (error: any) {
        console.error('获取用户信息失败:', error)
        ElMessage.error(error.response?.data?.message || '获取用户信息失败')
      } finally {
        loading.value = false
      }
    }

    // 切换编辑模式
    const toggleEditMode = () => {
      editMode.value = true
      // 重置密码字段
      profileForm.currentPassword = ''
      profileForm.newPassword = ''
      profileForm.confirmPassword = ''
    }

    // 取消编辑
    const cancelEdit = () => {
      editMode.value = false
      // 恢复原始数据
      profileForm.realName = userInfo.value.realName || ''
      profileForm.department = userInfo.value.department || ''
      profileForm.phone = userInfo.value.phone || ''
      profileForm.email = userInfo.value.email || ''
      profileForm.currentPassword = ''
      profileForm.newPassword = ''
      profileForm.confirmPassword = ''
    }

    // 保存个人信息
    const saveProfile = async () => {
      try {
        // 验证表单
        const valid = await profileFormRef.value.validate()
        if (!valid) return

        // 如果要修改密码，验证当前密码
        if (profileForm.newPassword && !profileForm.currentPassword) {
          ElMessage.error('修改密码时必须提供当前密码')
          return
        }

        saving.value = true

        const updateData: any = {
          realName: profileForm.realName,
          department: profileForm.department,
          phone: profileForm.phone,
          email: profileForm.email
        }

        // 如果要修改密码
        if (profileForm.newPassword) {
          updateData.currentPassword = profileForm.currentPassword
          updateData.newPassword = profileForm.newPassword
          updateData.confirmPassword = profileForm.confirmPassword
        }

        const response = await userService.updateProfile(updateData)
        
        ElMessage.success(response.data.message || '个人信息更新成功')
        
        // 更新本地用户信息
        if (response.data.user) {
          userInfo.value = response.data.user
        }
        
        editMode.value = false
        
        // 如果修改了密码，提示重新登录
        if (profileForm.newPassword) {
          ElMessageBox.alert('密码已更新，为了安全考虑，请重新登录', '提示', {
            confirmButtonText: '确定',
            callback: () => {
              // 可以在这里添加登出逻辑
              window.location.reload()
            }
          })
        }
        
      } catch (error: any) {
        console.error('更新个人信息失败:', error)
        ElMessage.error(error.response?.data?.message || '更新个人信息失败')
      } finally {
        saving.value = false
      }
    }

    // 获取角色标签类型
    const getRoleTagType = (role: string) => {
      switch (role) {
        case 'ADMIN': return 'danger'
        case 'TEACHER': return 'warning'
        case 'STUDENT': return 'success'
        default: return 'info'
      }
    }

    // 获取角色显示名称
    const getRoleDisplayName = (role: string) => {
      switch (role) {
        case 'ADMIN': return '管理员'
        case 'TEACHER': return '教师'
        case 'STUDENT': return '学生'
        default: return '未知'
      }
    }

    // 格式化日期
    const formatDate = (dateStr: string) => {
      if (!dateStr) return ''
      return new Date(dateStr).toLocaleString('zh-CN')
    }

    onMounted(() => {
      loadUserProfile()
    })

    return {
      loading,
      saving,
      editMode,
      userInfo,
      profileForm,
      profileFormRef,
      profileRules,
      toggleEditMode,
      cancelEdit,
      saveProfile,
      getRoleTagType,
      getRoleDisplayName,
      formatDate,
      Edit
    }
  }
})
</script>

<style lang="scss" scoped>
.profile-page {
  max-width: 800px;
  margin: 0 auto;
  
  .profile-card {
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
    border: none;
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 16px;
      font-weight: 500;
      color: #333;
      
      .edit-buttons {
        display: flex;
        gap: 10px;
      }
    }
  }
  
  .profile-content {
    min-height: 400px;
  }
  
  .view-mode {
    .user-info {
      .info-item {
        display: flex;
        align-items: center;
        margin-bottom: 20px;
        
        label {
          min-width: 120px;
          font-weight: 500;
          color: #666;
        }
        
        span {
          color: #333;
          flex: 1;
        }
        
        .el-tag {
          margin: 0;
        }
      }
    }
  }
  
  .edit-mode {
    .profile-form {
      max-width: 600px;
      
      .form-tip {
        font-size: 12px;
        color: #999;
        margin-top: 5px;
      }
    }
  }
  
  .el-button {
    &.el-button--primary {
      background-color: #424242;
      border-color: #424242;
      
      &:hover, &:focus {
        background-color: #333333;
        border-color: #333333;
      }
    }
  }
  
  .el-divider {
    margin: 30px 0 20px 0;
  }
}
</style> 